1455D - Sequence and Swaps - CodeForces Solution


dp greedy sortings *1600

Please click on ads to support us..

Python Code:


def solve():
    n, x = [int(x) for x in input().split()]
    a = [int(x) for x in input().split()]

    def isSorted():
        for i in range(n-1):
            if a[i] > a[i+1]: return False
        return True

    def getFirst():
        for i in range(n):
            if a[i] > x:
                return i
        return -1

    cnt = 0
    while not isSorted():
        idx = getFirst()
        if idx == -1:
            print(-1)
            return
        else:
            a[idx], x = x, a[idx]
            cnt += 1
        
    if not isSorted(): print(-1)
    else: print(cnt)

for _ in range(int(input())):
    solve()

C++ Code:

#include <bits/stdc++.h>
using namespace std;

typedef unsigned long long ull;
typedef long long ll;
typedef long double ld;

const ll mod  = 1e9+7;
const ld eps  = 1e-9 ;
const ll maxn = 1e5+1;
const ll inf  = 1e15 ;
const ll minf = -inf ;

#define mp make_pair
#define pb push_back
#define endl "\n"

bool check(vector<ll> &v)
{
    for(ll i=1 ; i<v.size() ; ++i)
    {
        if(v[i]<v[i-1]) return false;
    }
    return true;
}

bool solve()
{
    ll n,x;
    cin >> n >> x;
    vector<ll> v(n);

    for(ll i=0 ; i<n ; ++i) cin >> v[i];

    if(check(v))
    {
        cout << 0 << endl;
        return true;
    }

    for(ll i=0,cnt=0 ; i<n ; ++i)
    {
        if(v[i]>x)
        {
            swap(v[i],x);
            cnt++;
            if(check(v))
            {
                cout << cnt << endl;
                return true;
            }
        }
    }
    
    return false;    
}

int main()
{
    ios_base :: sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    #ifdef EPSILON
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    freopen("error.txt","w",stderr);
    #endif

    ll t=1;
    cin >> t;

    while(t--)
    {
        if(solve()){}
        else
        
            cout << -1 << endl;
    }

    return 0;
} 


Comments

Submit
0 Comments
More Questions

415. Add Strings
22. Generate Parentheses
13. Roman to Integer
2. Add Two Numbers
515. Find Largest Value in Each Tree Row
345. Reverse Vowels of a String
628. Maximum Product of Three Numbers
1526A - Mean Inequality
1526B - I Hate 1111
1881. Maximum Value after Insertion
237. Delete Node in a Linked List
27. Remove Element
39. Combination Sum
378. Kth Smallest Element in a Sorted Matrix
162. Find Peak Element
1529A - Eshag Loves Big Arrays
19. Remove Nth Node From End of List
925. Long Pressed Name
1051. Height Checker
695. Max Area of Island
402. Remove K Digits
97. Interleaving String
543. Diameter of Binary Tree
124. Binary Tree Maximum Path Sum
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
501A - Contest
160A- Twins
752. Open the Lock
1535A - Fair Playoff
1538F - Interesting Function